package cn.jbolt.core.enjoy.directive;

import cn.jbolt.core.util.JBoltDateUtil;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * Year指令
 *
 * @ClassName: YearDirective
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2022年3月5日22:47:57
 */
public class YearDirective extends Directive {

	private Expr valueExpr;
	private int paraNum;

	@Override
	public void setExprList(ExprList exprList) {
		this.paraNum = exprList.length();
		if (paraNum == 1) {
			this.valueExpr = exprList.getExpr(0);
		} else {
			throw new ParseException("Wrong number parameter of #year directive, one parameter allowed at most",
					location);
		}
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		if (paraNum == 0) {
			write(writer, JBoltDateUtil.getYearStr());
		} else {
			outputValue(env, scope, writer);
		}
	}

	/**
	 * 输出处理后的value值
	 *
	 * @param env
	 * @param scope
	 * @param writer
	 */
	private void outputValue(Env env, Scope scope, Writer writer) {
		Object value = this.valueExpr.eval(scope);
		if (value == null || value.toString().length() == 0) {
			write(writer, JBoltDateUtil.getYearStr());
		}else {
			write(writer, value.toString());
		}

	}

}
